package com.autotest.nore.common.utils;

import com.fasterxml.jackson.databind.JsonNode;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class processVariableUtils {

    /*
      处理JSON
     */
    public static String processJsonNode(JsonNode node, Map<String, String> variables) {
        String content = node.toString();
        content=replacePlaceholders(content);
        for (Map.Entry<String, String> entry : variables.entrySet()) {
            content = content.replace("{{" + entry.getKey() + "}}", entry.getValue());
            content=ReplaceVariableUtils.handleVarible(content);
        }
        return content;
    }

    public static String replacePlaceholders(String content) {
        // 定义正则表达式模式
        String regex = "\\{\\{\\$(.*?)\\}\\}";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(content);

        // 使用StringBuffer来构建新的字符串
        StringBuffer replacedContent = new StringBuffer();

        // 查找所有匹配项并进行替换
        while (matcher.find()) {
            // 调用ReplaceVariableUtils.handleFunction并获取其结果
            String replacement = ReplaceVariableUtils.handleFunction(matcher.group(1));
            // 将匹配到的部分替换为新值
            matcher.appendReplacement(replacedContent, Matcher.quoteReplacement(replacement));
        }

        // 添加剩余未匹配部分到结果中
        matcher.appendTail(replacedContent);

        // 返回处理过的内容
        return replacedContent.toString();
    }
    /*
       处理String
    */
    public static String processStr(String str, Map<String, String> variables){
        String content= str;
        content=replacePlaceholders(content);
        for (Map.Entry<String, String> entry : variables.entrySet()) {
            content = content.replace("{{" + entry.getKey() + "}}", entry.getValue());
            content=ReplaceVariableUtils.handleVarible(content);
        }
        return content;
    }


}
